//
//  HeaderViewController.m
//  Quick_News
//
//  Created by 曾凯峻 on 15/1/29.
//  Copyright (c) 2015年 zkj. All rights reserved.
//

#import "HeaderViewController.h"

@interface HeaderViewController () 

@end

@implementation HeaderViewController
//内存管理
- (void)dealloc
{
    [self.tableView release];
    [self.tableArr release];
    [super dealloc];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
    self.page = 0;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //数组初始化
    self.tableArr = [NSMutableArray array];
    if (!self.tableArr) {
                
        [self creatView];
        [self headRefreshing];
    }
    else {
        [self creatView];
        [self headRefreshing];
    }
    
    
    
}

- (void)headRefreshing
{
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.tableView headerBeginRefreshing];
    self.tableView.headerPullToRefreshText = @"下拉刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"正在刷新中,请稍后";
    
    self.tableView.footerPullToRefreshText = @"上拉加载更多数据";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据";
    self.tableView.footerRefreshingText = @"正在加载中,不客气";
}

//加载方法
- (void)headerRereshing
{
    
        //自动刷新
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.tableView reloadData];
 
        NSString *str = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/headline/T1348647853363/0-140.html"];
        
        __block HeaderViewController *headerVC = self;
        // 创建AFHTTPRequestOperationManager对象
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        // 根据服务器响应内容的不同,为AFHTTPRequestOperationManager对象指定不同的解析器.对象默认的解析器要求服务器响应的是JSON数据或者Plist数据.
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
        [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            // NSLog(@"JSON:%@", responseObject);
            [self.tableArr removeAllObjects];

            NSMutableArray *tempArr = [responseObject objectForKey:@"T1348647853363"];
 
            for (NSDictionary *dic in tempArr) {
                TopNews *news = [[TopNews alloc] init];
                [news setValuesForKeysWithDictionary:dic];
                // NSLog(@"%@", dic);
                if (![news.digest isEqual:@""]) {
                    if (![news.source isEqual:@"网易新媒体"]) {
                    if (![news.TAG isEqual:@"LIVE"]) {
                    [headerVC.tableArr addObject:news];
                        }
                    }
                    //  NSLog(@"%@", self.myView.tableArr);
                }
                [news release];
            }
            [self.tableView reloadData];
 
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起" message:@"网络加载出错啦" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
            NSLog(@"Error:%@", error);
        }];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
    
}


- (void)footerRereshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];

        NSString *str = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/headline/T1348647853363/%ld-20.html", self.page + 140];
        NSLog(@"page%ld", self.page);
        self.page += 20;
        
        __block HeaderViewController *headerVC = self;
        // 创建AFHTTPRequestOperationManager对象
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        // 根据服务器响应内容的不同,为AFHTTPRequestOperationManager对象指定不同的解析器.对象默认的解析器要求服务器响应的是JSON数据或者Plist数据.
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            // NSLog(@"JSON:%@", responseObject);
            NSMutableArray *tempArr = [responseObject objectForKey:@"T1348647853363"];

            for (NSDictionary *dic in tempArr) {
                TopNews *news = [[TopNews alloc] init];
                [news setValuesForKeysWithDictionary:dic];
                // NSLog(@"%@", dic);
                if (![news.digest isEqual:@""]) {
                    if (![news.source isEqual:@"网易新媒体"]) {
                        [headerVC.tableArr addObject:news];
                    }
                    //  NSLog(@"%@", self.myView.tableArr);
                }
                [news release];
            }
            [self.tableView reloadData];

            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起" message:@"网络加载出错啦" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
            NSLog(@"Error:%@", error);
        }];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView footerEndRefreshing];
    });
    
}


//创建视图
- (void)creatView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 100)];
    //设置代理
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [self.tableView release];
}

//设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"reused";
    TopNewCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:str];
    if (!cell) {
        cell = [[[TopNewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
    }
    TopNews *news = [self.tableArr objectAtIndex:indexPath.row];
  //  NSLog(@"%@======", self.tableArr);
    cell.titleLabel.text = news.title;
    cell.digestLabel.text = news.digest;
    cell.ptimeLabel.text = news.ptime;
    [cell.imgsrcImage setImageWithURL:[NSURL URLWithString:news.imgsrc]];
    return cell;
}
//一行cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableArr.count;
}
//点击跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HeaderInfoViewController *headerInfoVC = [[HeaderInfoViewController alloc] init];
    headerInfoVC.topNews = [self.tableArr objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:headerInfoVC animated:YES];
    [headerInfoVC release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
